<?php
require_once BaseUtil::getModulePath("base")  .  '/controllers/BaseController.php';
require_once BaseUtil::getModulePath('dbgrid') . '/DBGrid.php';
require_once BaseUtil::getModulePath ("systemlog") . '/services/EmailLogService.php';
require_once BaseUtil::getModulePath ("systemlog") . '/services/EmailService.php';
require_once BaseUtil::getModulePath ("customer") . '/services/CustomerService.php';
require_once BaseUtil::getModulePath("component")  .  '/MailUtil.php';
class SystemLog_EmailController extends BaseController {
    public function init() {
        parent::init();
        $this->view->script = array('lib/ui.dialog.js','Email.js');
        $this->addLocaleData('emaillog');
        $this->addLocaleData('customer');
    }
    
    public function indexAction(){
    	
    }
    
    public function sendAction(){
    	
    	
    	$certfStr = HttpUtil::getPostString('certfStr');
    	$rankStr = HttpUtil::getPostString('rankStr');
    	$emailStr = HttpUtil::getPostString('emailStr');
        $subject = HttpUtil::getPostString("subject");
        $content = HttpUtil::getPostString("content");
      
      
        
    	$customerService = new CustomerService();
    	if($certfStr){
    	    $customersOfCertf = $customerService->getCustomersByCertf($certfStr);
    	}
    	if($rankStr){
    	   $customersOfRank = $customerService->getCustomersByRank($rankStr);
    	}
    	$emailArr = explode(",",$emailStr);
    	if($customersOfCertf){
    	    foreach($customersOfCertf as $customer) {
    		    if(!in_array($customer["email"],$emailArr)){
    			    array_push($emailArr,$customer["email"]);
    		    }
    	    }
    	}
    	if($customersOfRank){
            foreach($customersOfRank as $customer) {
    		    if(!in_array($customer["email"],$emailArr)){
    			    array_push($emailArr,$customer["email"]);
    		    }
    	    }
    	}
    	
    	$emailService = new EmailService();
    	$sendToEmails = '';
    	foreach ($emailArr as $email){
    		if($email){
    		   MailUtil::sendMail(trim($email), $subject, $content);
    		   if($sendToEmails){
    		   	   $sendToEmails .= ','.$email;
    		   } else {
    		   	   $sendToEmails .= $email;
    		   }
    		}
    	}
    	
    	$admin = $_SESSION['loginUser']['uname'];
    	
    	$email_type = 8;
        $send_to = "$sendToEmails";
        $send_cc = "";
        $description = "后台管理员{$admin}群发邮件";
        $emailInfo = array(
            'email_type' => $email_type,
            'send_to' => $send_to,
            'send_cc' => $send_cc,
            'description' => $description            
        );
        $emailService->addEmailLog($emailInfo);
    	
    	
    	echo 1;
    	exit();
    	
    	
    }
    
}